const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const shop = require('../../services/shop.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    wx_login_code:'',
    userInfo: null,
    show_user_btn:false,

    shop:{},
    links:[
      {LinkUrl:'/pages/video/index?sort=22',Title:'电脑版ECU维修视频',type:"switchTab"},
      {LinkUrl:'/pages/video/index?sort=23',Title:'尿素泵维修视频',type:"switchTab"},
      {LinkUrl:'/pages/video/index?sort=24',Title:'维修设备使用视频',type:"switchTab"},
      {LinkUrl:'/pages/catalog/catalog?id=1291533657424662528',Title:'产品置换',type:"switchTab"},
    ],
    newGoods: [],
    hotGoods: [],
    topics: [],
    brand: [],
    floorGoods: [],
    banner: [],
    channel: [],
    FileHost:'',

    RoleID:0,
    video:null,
    is_vip:false
  },
  onLoad: function (options) {
    var that=this;
    this.setData({ FileHost: api.FileHost });
    this.setData({page_height:wx.getSystemInfoSync().windowHeight});
    
    var shop=wx.getStorageSync('shop');
    this.setData({shop:shop});

    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo != "") 
    {
      this.setData({userInfo: userInfo});
      if(userInfo.UserName===null)
      {
        this.setData({show_user_btn:true});
      }
      that.setData({RoleID:userInfo.RoleID});
      if(userInfo.ST==2&&userInfo.RoleID>0)
      {
        this.setData({is_vip:true});
        var roleInfo=wx.getStorageSync('roleInfo');
        that.setData({roleInfo:roleInfo});
      }
    } 
    else 
    {      
      wx.login({
        success: res => {
          that.setData({wx_login_code:res.code});
        }
      })
    }
    
    var page_height=417+200+200+375*3+wx.getSystemInfoSync().screenWidth*0.6;
    this.setData({page_height:page_height});

    var IsDebug=wx.getStorageSync('IsDebug');
    this.setData({IsDebug:IsDebug});
    if(IsDebug=="0")
    {
      wx.setTabBarItem({
        index: 1,
        text: '装机视频',
        iconPath: '/static/images/ic_menu_topic_nor.png',
        selectedIconPath: '/static/images/ic_menu_sort_pressed.png'
      });
    }
    this.getIndexData();
  },
  onReady: function () {
    // 页面渲染完成
    
  },
  onShow: function () {
    // 页面显示
    //shop.setPageTitle();//显示商家名称
     
  },
  onPageScroll (e) 
  {  
    var that=this;
    const query = wx.createSelectorQuery()
    query.select('#page').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
      //console.log("########################################")
      //console.log(res[1].scrollHeight)
      that.setData({page_height:res[1].scrollHeight});
      //console.log("########################################")
    })
  },
  onHide: function () {
    // 页面隐藏
    this.isShow = false;
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function () {
    return {
      title:app.globalData.shopInfo.ShopName,
      desc: app.globalData.shopInfo.Summary,
      path: '/pages/start/index?id='+wx.getStorageSync('ShopID')
    }
  },
  onPullDownRefresh(){
	  	// 增加下拉刷新数据的功能
	    var self = this;
	    this.getIndexData();
 },
 reLoction:function(e){
   var page_url=e.currentTarget.dataset.url;
   wx.reLaunch({url:page_url});

 },
 select_cate:function(e){
  var id=e.currentTarget.dataset.id;
  wx.reLaunch({url:"/pages/catalog/catalog?id="+id});  
 },
  TencentMap:function(){
    var that = this;
    var o = {
      name: that.data.shop.ShopAddress,
      location: {
        lat: that.data.shop.GPS_Y,
        lng: that.data.shop.GPS_X
      }
    };
    wx.navigateToMiniProgram({
      appId: 'wx7643d5f831302ab0',
      path:"pages/multiScheme/multiScheme?endLoc=" + JSON.stringify(o) + "&qbMode=0",
      success(res) {
        // 打开成功
      }
    });
  },
  call:function(){
    var phone=this.data.shop.ShopTel;
    wx.makePhoneCall({phoneNumber: phone});
  },
  getIndexData: function () {
    let that = this;
    var data = new Object();
    var shopid = wx.getStorageSync('ShopID');
    var is_vip=that.data.is_vip;
    /*util.request(api.IndexUrlHotGoods, { Num: 4, IsHot: 1, ShopID: 0},'GET').then(function (res) {
      if (res.Status === 100) 
      {
        if(is_vip)
        {
          var roleInfo=that.data.roleInfo;
          for(var i=0;i<res.Data.length;i++)
          {
            res.Data[i].Price=(res.Data[i].Price*roleInfo.Percent).toFixed(2);
          }
        }        
        that.setData({hotGoods:res.Data});
      }
    });

    
    util.request(api.IndexUrlBrand, {ShopID:0, IsTop:1},'GET').then(function (res) {
      if (res.Status === 100) 
      {
        data.brand = res.Data;
        that.setData(data);
      }
    });
    
    util.request(api.IndexUrlTopic, { ShopID:0, Num:4, SortID: 2, IsValid:1},'GET').then(function (res) {
      if (res.Status === 100) 
      {
        data.topics = res.Data
        that.setData(data);
      }
    });
    util.request(api.IndexUrlCategory).then(function (res) {
      if (res.errno === 0) {
        data.floorGoods = res.data.categoryList
        that.setData(data);
      }
    });
    */
   util.request(api.GetVideoList, {Page:1,PageSize:1,ST:1},"GET").then(function (res) 
   {
     console.log(res);
     if (res.Status == 100) 
     { 
       
       if(res.Data.Models.length>0)
       {
         var info=res.Data.Models[0];
          that.setData({video: info});
       }
       
     }
   });

    util.request(api.LinkList, {ShopID:0, SortID:4},"GET").then(function (res) 
    {
      console.log(res);
      if (res.Status == 100) 
      { 
        that.setData({ banner: res.Data});
      }
    });
    /*util.request(api.LinkList, {ShopID:0, SortID:18},"GET").then(function (res) 
    {
      console.log(res);
      if (res.Status == 100) 
      { 
        that.setData({ links: res.Data});
      }
    });*/
    util.request(api.ProSortList,{Pid:'0'},"GET").then(function (res) {
      if (res.Status === 100) 
      {
        
        var channel=new Array();
        res.Data.map(function(item,i){
          if(i<=5)
          {
            channel.push(item);
          }
        });
        that.setData({ channel: channel });

       /* var arr=new Array();
        var arr2=new Array();
        res.Data.map(function(item,i){
            if(i<2)
            {
              arr.push(item);
              arr2.push(item.Id);
            }
        });
        that.setData({sorts:arr});
        var ids=arr2.join(',');
        
        util.request(api.GetHomeProductList, {ids:ids},'GET').then(function (res) 
        {
          if (res.Status === 100) 
          {
            that.setData({floorGoods:res.Data});
          }
        });*/



      }
    });
    

  },
  addToCart: function (e) {
    var that = this;
    var productid=e.currentTarget.dataset.id;
    
    var userid='';
    if(that.data.userInfo!=null)
    {
      userid = that.data.userInfo.Id;
      var is_vip=that.data.is_vip;
      if(is_vip==false)
      {
        wx.showModal({
          title: '提示',
          content:'只有认证会员才能购买。立即升级请点击"确定"按钮',
          success(res1) 
          {
            if (res1.confirm) 
            {
              wx.navigateTo({url: '/pages/auth/note/index'});
            }
            else if (res1.cancel) 
            {
              return;
            }
          }
        })
        return;
      }
    }
    else
    {
      util.showErrorToast('请登录后再购买');
      setTimeout(function(){
        wx.navigateTo({url: '/pages/auth/mobile/mobile'});
      },1500);
      return;
    }

    

    var shopid= wx.getStorageSync('ShopID')||1;
    var pd = {ShopID:shopid, UserID: userid, ProductID: productid, ProSizeID:'', ItemNum:1};
    //添加到购物车
    util.request(api.SetCart,pd, 'GET').then(function (res) 
    {
        if (res.Status == 100) 
        {  
          wx.showModal({
            title: '提示',
            content: '添加成功,是否立即进入购物车 ？',
            success(res1) 
            {
              if (res1.confirm) 
              {
                wx.reLaunch({url: '/pages/cart/cart'})
              }
              else if (res1.cancel) 
              {
                 
              }              
            }
          })

        } 
        else 
        {
          wx.showToast({image: '/static/images/icon_error.png',title:'购买失败',mask: true});
          return;
        }

      });
    

  },
  //------------------------------------------------
  getPhoneAndLogin: function (e) {
    let that = this;
    console.log(e);  
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    if (e.detail.errMsg !="getPhoneNumber:ok") 
    {
      return;
    }

    //wx.showLoading({mask: true});

      // 检查登录态是否过期
      wx.checkSession({
        success(res) 
        {
          var data={
            jscode:that.data.wx_login_code,
            encryptedData:encryptedData,
            IV:iv
          };
          util.request(api.GetPhoneNumber,data, 'POST').then(function (res) 
          {
            if (res.Status === 100) 
            {
              var extInfo=res.Data;
              that.setData({extInfo: extInfo});
              wx.setStorageSync('extInfo', extInfo);
              //------------------开始注册---------------------------------
 
              var userInfo = wx.getStorageSync('userInfo');
              var shopid = wx.getStorageSync('ShopID') || 1;
              var uid = wx.getStorageSync('uid') || '';

              var pd = {
                OpenID: extInfo.openid,
                Mobile: extInfo.mobile,
                UserName:'',
                UserIcon: '',
                FromID: uid,
                ShopID: shopid
              };
              util.request(api.WeChatLogin, pd, 'POST').then(function (res) {
                if (res.Status === 100) 
                {
                  wx.setStorageSync('userInfo', res.Data);
                  wx.reLaunch({url: '/pages/index/index'});                  
                } 
                else 
                {
                  wx.showModal({content: '1操作发生错误',
                    success(res1) 
                    {
                      wx.reLaunch({url: '/pages/index/index'});
                    }
                  })

                }
              });


              //------------------结束注册---------------------------------
            } 
            else 
            {
              wx.showModal({content: '2操作发生错误',
                    success(res1) 
                    {
                      wx.reLaunch({url: '/pages/index/index'});
                    }
                  })
            }
          });
        },
        fail(err) 
        {
            // session_key 已经失效，需要重新执行登录流程
            wx.login({
                success: res => {
                    that.data.wx_login_code = res.code
                }
            })
        }
    })
  },
  update_user:function(e){
    var that = this;
    var tempInfo = e.detail.userInfo;
    that.setData({
      tempInfo: e.detail.userInfo
    });
    var userInfo = wx.getStorageSync('userInfo');
    console.log(tempInfo);
    if (userInfo != '') {
      userInfo.UserIcon = tempInfo.avatarUrl;
      userInfo.UserName = tempInfo.nickName;
      var pd = {
        OpenID: userInfo.OpenID,
        Mobile: userInfo.Mobile,
        UserName: tempInfo.nickName,
        UserIcon: tempInfo.avatarUrl
      };
      util.request(api.UpdateUserIcon, pd, 'POST').then(function (res) {
        if (res.Status === 100) 
        {
          wx.setStorageSync('userInfo', userInfo);
          wx.reLaunch({url: '/pages/index/index'});
        } 
        else
        {
          wx.showModal({
            title: 'ERROR',
            content: '操作发生错误'
          });
        }
      });
    }
  }
//--------------------------------------------------
})
